﻿namespace MPNet6.Server;

internal static class NetworkStreamExtensions
{
    public static byte SendAndRecieve(this NetworkStream? stream, string str)
    {
        return stream.SendAndRecieve(Encoding.ASCII.GetBytes(str));
    }
    public static byte SendAndRecieve(this NetworkStream? stream, byte b) => stream.SendAndRecieve(new byte[] { b });
    /// <summary>
    /// 
    /// </summary>
    /// <param name="stream"></param>
    /// <param name="bytes"></param>
    /// <returns>0：发送失败；1：表示客户端为长期在线的；2：表示客户端为仅接收一次消息</returns>
    public static byte SendAndRecieve(this NetworkStream? stream, byte[] bytes)
    {
        byte ret = 0;
        try
        {
            if (stream != null)
            {
                byte[] buffer = new byte[8];
                stream.Write(bytes);
                var len = stream.Read(buffer);
                if (len > 0)
                    ret = buffer[0];
            }
        }
        catch (Exception)
        {
        }
        return ret;
    }
}
